#include "stdafx.h"
#include "SerialPort.h"


SerialPort::SerialPort(void)
{
}


SerialPort::~SerialPort(void)
{
}

int SerialPort::connect()
{
	return connect(L"COM1");
}

int SerialPort::connect (wchar_t *device)
{
	DWORD err;
	hSerial= CreateFile(device, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (hSerial==INVALID_HANDLE_VALUE)
	{
		err=GetLastError();
		if (err==ERROR_FILE_NOT_FOUND)
			fprintf(stderr, "No such serial port!\n");
		else
			fprintf(stderr, "Cannot open serial port! Error code %d\n", err);
		return -1;
	}
	// Configure the seerial port, reading current config and write back new config
	LPDCB dcbSerialParams=new(DCB);
	if(!GetCommState(hSerial, dcbSerialParams))
	{
		fprintf(stderr, "Cannot get serial port state!\n");
		return -1;
	}
	dcbSerialParams->BaudRate=CBR_9600;
	dcbSerialParams->ByteSize=8;
	dcbSerialParams->Parity=NOPARITY;
	dcbSerialParams->StopBits=TWOSTOPBITS;

	if (!SetCommState(hSerial, dcbSerialParams))
	{
		fprintf(stderr, "Cannot set	port state!\n");
		return -1;
	}
	//Setting a timeout means that we don't wait forever for more data to come in
	LPCOMMTIMEOUTS timeouts=new(COMMTIMEOUTS);
	// Maximum interval between characters
	timeouts->ReadIntervalTimeout=50;
	// Total timeout = ReadTotalTimeoutMultiplier*# of characters read

	// = ReadTotalTimeoutConstant.
	timeouts->ReadTotalTimeoutConstant=50;
	timeouts->ReadTotalTimeoutMultiplier=50;
	timeouts->WriteTotalTimeoutConstant=50;
	timeouts->WriteTotalTimeoutMultiplier=10;
	if(!SetCommTimeouts(hSerial, timeouts))
	{
		fprintf(stderr, "Cannot set timeouts!\n");
		return -1;
	}
	return 1;
}

void SerialPort::disconnect(void)
{

	CloseHandle(hSerial);
	hSerial = INVALID_HANDLE_VALUE;
}

int SerialPort::sendArray(char buffer[], int len)
{
	DWORD bytesRead;
	// Writing is done using WriteFile
	if (!WriteFile(hSerial, buffer, len, &bytesRead, NULL))
	{
		fprintf(stderr, "Unable to write serial port\n");
	}

	return bytesRead;
}
int SerialPort::getArray (char buffer[], int len)
{
	DWORD bytesRead;
	if (!ReadFile(hSerial, buffer, len, &bytesRead,NULL))
	{
		fprintf(stderr, "Unable to read serial port\n");
		bytesRead=0;
	}
	else
	{

		if(bytesRead>0)
			printf("%s\n", buffer);
	}

	return bytesRead;
}